package com.jiyici.fragment;

import android.content.Intent;
import android.graphics.Point;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.jiyici.DragSortController;
import com.jiyici.DragSortListView;
import com.jiyici.EditItemActivity;
import com.jiyici.DragSortListView.DropListener;
import com.jiyici.ItemActivity;
import com.jiyici.R;
import com.jiyici.controller.DataManager;
import com.jiyici.controller.DataManager.DataListener;
import com.jiyici.data.ClientDBHelper;
import com.jiyici.model.Category;
import com.jiyici.model.Item;
import com.jiyici.utils.Global;
import com.jiyici.view.ItemView;

public class ItemListFragment extends BaseFragment implements DataListener {
    
    private DragSortListView mItemContainer;
    private DragSortAdapter mAdapter = new DragSortAdapter();
    
    private LayoutInflater mLayoutInflater;
    
    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        menu.add(R.string.actionbar_item_new_item).setIcon(R.drawable.ic_content_new)
        .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
        super.onCreateOptionsMenu(menu, inflater);
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (getText(R.string.actionbar_item_new_item).equals(item.getTitle())) {
            Intent intent = new Intent(getActivity(), EditItemActivity.class);
            startActivity(intent);
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        
        mItemContainer = (DragSortListView) view.findViewById(R.id.item_list);
        mItemContainer.setDividerHeight(0);
        mItemContainer.setAdapter(mAdapter);
        mItemContainer.setDropListener(mAdapter);
        mItemContainer.setDragEnabled(true);

        SectionController sc = new SectionController(mItemContainer, mAdapter);
        mItemContainer.setFloatViewManager(sc);
        mItemContainer.setOnTouchListener(sc);
        mItemContainer.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Object object = DataManager.getDataList().get(position);
                if (object instanceof Item) {
                    Item item = (Item) object;
                    Intent intent = new Intent(getActivity(), ItemActivity.class);
                    intent.putExtra("item", item);
                    startActivity(intent);
                }
            }
            
        });
        
        mLayoutInflater = LayoutInflater.from(getActivity());
        new AsyncTask<Void, Void, Void>() {

            @Override
            protected Void doInBackground(Void... params) {
                ClientDBHelper.initDbHelper(Global.APP_CONTEXT, DataManager.getUser());
                return null;
            }

            @Override
            protected void onPostExecute(Void result) {
                DataManager.startLoadData();
            }
            
        }.execute();
        
        return view;
    }
    
    @Override
    public void onItemCatgoryChanged() {
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void onRecordChanged() {
        //NO-OP
    }

    private class SectionController extends DragSortController {

        private int mPos;
        // private int mDivPos;

        private DragSortAdapter mAdapter;

        DragSortListView mDslv;

        public SectionController(DragSortListView dslv, DragSortAdapter adapter) {
            super(dslv, R.id.drag_handler, DragSortController.ON_LONG_PRESS, 0);
            setRemoveEnabled(false);
            mDslv = dslv;
            mAdapter = adapter;
            // mDivPos = adapter.getDivPosition();
        }

        @Override
        public int startDragPosition(MotionEvent ev) {
            int res = super.dragHandleHitPosition(ev);
            if (res > DataManager.getDataList().size() - 1 || res < 0)
                return DragSortController.MISS;
            if (DataManager.getDataList().get(res) instanceof Category) {
                return DragSortController.MISS;
            }
            return res;

            // int width = mDslv.getWidth();
            //
            // if ((int) ev.getX() < width / 3) {
            // return res;
            // } else {
            // return DragSortController.MISS;
            // }
        }

        @Override
        public View onCreateFloatView(int position) {
            mPos = position;

            View v = mAdapter.getView(position, null, mDslv);
            v.setBackgroundDrawable(getResources().getDrawable(R.drawable.bg_handle_section1));
            v.getBackground().setLevel(10000);
            return v;
        }

        private int origHeight = -1;

        @Override
        public void onDragFloatView(View floatView, Point floatPoint, Point touchPoint) {
            // final int first = mDslv.getFirstVisiblePosition();
            // final int lvDivHeight = mDslv.getDividerHeight();
            //
            // if (origHeight == -1) {
            // origHeight = floatView.getHeight();
            // }
            //
            // View div = mDslv.getChildAt(mDivPos - first);
            //
            // if (touchPoint.x > mDslv.getWidth() / 2) {
            // float scale = touchPoint.x - mDslv.getWidth() / 2;
            // scale /= (float) (mDslv.getWidth() / 5);
            // ViewGroup.LayoutParams lp = floatView.getLayoutParams();
            // lp.height = Math.max(origHeight, (int) (scale * origHeight));
            // Log.d("mobeta", "setting height "+lp.height);
            // floatView.setLayoutParams(lp);
            // }
            //
            // if (div != null) {
            // if (mPos > mDivPos) {
            // // don't allow floating View to go above
            // // section divider
            // final int limit = div.getBottom() + lvDivHeight;
            // if (floatPoint.y < limit) {
            // floatPoint.y = limit;
            // }
            // } else {
            // // don't allow floating View to go below
            // // section divider
            // final int limit = div.getTop() - lvDivHeight -
            // floatView.getHeight();
            // if (floatPoint.y > limit) {
            // floatPoint.y = limit;
            // }
            // }
            // }
        }

        @Override
        public void onDestroyFloatView(View floatView) {
            // do nothing; block super from crashing
        }

    }
    
    private final class DragSortAdapter extends BaseAdapter implements DropListener {

        @Override
        public int getCount() {
            return DataManager.getDataList().size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = null;
            Object data = DataManager.getDataList().get(position);
            if (data instanceof Category) {
                Category category = (Category) data;
                view = mLayoutInflater.inflate(R.layout.category_divider, parent, false);
                TextView tv = (TextView) view;
                tv.setText(category.name);
            } else if (data instanceof Item) {
                Item item = (Item) data;
                ItemView itemView = new ItemView(getActivity());
                itemView.setId(R.id.drag_handler);
                itemView.setItem(item);
                boolean displayDivider = true;
                if (position == getCount() - 1)
                    displayDivider = false;
                else if (DataManager.getDataList().get(position + 1) instanceof Category){
                    displayDivider = false;
                }
                itemView.displayDivider(displayDivider);
                view = itemView;
            }
            return view;
        }

        @Override
        public void drop(int from, int to) {
            if (from != to) {
                DataManager.changeOrderForDataList(from, to);
                notifyDataSetChanged();
            }
        }

        @Override
        public boolean areAllItemsEnabled() {
            return false;
        }

        @Override
        public boolean isEnabled(int position) {
            return (DataManager.getDataList().get(position) instanceof Item);
        }

    }

    
}
